package com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Collections;
import java.util.List;

/**
 * @author Fang Ruichuan
 * @date 2022-09-02 12:43
 */
@Configuration
public class RedisLuaConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @author Fang Ruichuan
     * @date 2022/9/2 12:47
     * @param lockKey
     * @param value
     * @return boolean 返回1-表示正常，0-表示限制访问
     */
    public boolean runLuaScript(String lockKey, String value) {
        List<String> keyList = Collections.singletonList(lockKey);

        // 执行脚本，删除锁
        DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/redisLock.lua")));
        redisScript.setResultType(String.class);
        String execute = redisTemplate.execute(redisScript, keyList, value);
        return "1".equals(execute);
    }

}
